//
//  TianjiadianpuTableViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/18.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire



//var param = [String:String]()

@available(iOS 9.0, *)
class TianjiadianpuTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate {

    

    var shopname = ""
    var address1 = ""
    var address2 = ""
    var shoplabel = ""
    var tel = ""
    var starttime = ""
    var endtime = ""
    var name = ""
    var content = ""
    
    var img = NSData()


    
    //var base64 = ""
    @IBOutlet weak var shopImg: UIImageView!
    
    @IBOutlet weak var dianmingTex: UITextField!
    
    //@IBOutlet weak var chengshiTex: UITextField!
    
    @IBOutlet weak var fenleiTex: UITextField!
    
    @IBOutlet weak var dizhiTex: UITextField!
    
    @IBOutlet weak var dianhuaTex: UITextField!
    
    @IBOutlet weak var kaishiTex: UITextField!
    
    //@IBOutlet weak var jieshuTex: UITextField!
    
    @IBOutlet weak var dianpuTex: UITextField!
    
    @IBAction func xiayibuBtn(_ sender: UIButton) {
        
//        let x = UserDefaults.standard.object(forKey: "user_id") as! NSDictionary
//        let y = x["name"]!
        shopname = dianmingTex.text!
        //address1 = chengshiTex.text!
        address2 = dizhiTex.text!
        shoplabel = fenleiTex.text!
        tel = dianhuaTex.text!
        starttime = kaishiTex.text!
        //endtime = jieshuTex.text!
        //name = "\(y)"
        content = dianpuTex.text!
        let telInt = Int(tel)
        if dianmingTex.text == "" || shopImg == nil || fenleiTex.text == "" || dizhiTex.text == "" || dianhuaTex.text == "" || kaishiTex.text == "" || dianpuTex.text == "" {
            self.noticeInfo("信息填写不全", autoClear: true, autoClearTime: 2)
        } else {
            if (telInt ?? Int()) != 0 {
            param = ["shopname":shopname,"address1":address1,"address2":address2,"shoplabel":shoplabel,"tel":tel,"starttime":starttime,"endtime":endtime,"name":name,"shoplat":"","shoplng":"","content":content]

            let sb = UIStoryboard(name: "Main", bundle:nil)
            let vc = sb.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController
            self.navigationController?.pushViewController(vc, animated: true)//present(vc, animated: true, completion: chuan)//pushViewController(vc, animated: true)
            } else if (telInt ?? Int()) == 0 {
                self.noticeInfo("电话填写错误", autoClear: true, autoClearTime: 2)
        }
        }
    }
    
    
    
    
    
    func tanchuang(){
        let alertVC = UIAlertController(title: "添加相片", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        let acXiangji = UIAlertAction(title: "相机拍摄", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            self.camera()
        }
        
        let acXiangce = UIAlertAction(title: "相册选取", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            self.photo()
        }
        let acCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acXiangji)
        alertVC.addAction(acXiangce)
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }

    func camera(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerControllerSourceType.camera
        self.present(pick, animated: true, completion: nil)
    }
    
    func photo(){
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerControllerSourceType.photoLibrary
        self.present(pick, animated: true, completion: nil)
    }
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dianmingTex.delegate = self
        //chengshiTex.delegate = self
        fenleiTex.delegate = self
        dizhiTex.delegate = self
        dianhuaTex.delegate = self
        kaishiTex.delegate = self
        //jieshuTex.delegate = self
        dianpuTex.delegate = self
        let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
        name = "\(x["name"]!)"
            let tap = UITapGestureRecognizer(target : self,action : #selector(tanchuang))
            tap.numberOfTapsRequired = 1
            shopImg.isUserInteractionEnabled = true
            shopImg.addGestureRecognizer(tap)
            
        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = false
    }
    
    func kbFrameChanged(_ notification : Notification){
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = kbRect.origin.y - UIScreen.main.bounds.height + 200
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
            self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/1.5)
        }
    }
    
    //MARK:- UIImagePickerControllerDelegate
    func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo
        info: [String :Any]){
        
        let type:String = (info[UIImagePickerControllerMediaType]as!String)
        
        if type=="public.image"
        {
            let img = info[UIImagePickerControllerOriginalImage] as? UIImage
            self.shopImg.image = img
            let datata = UIImageJPEGRepresentation(self.shopImg.image!, 0.3)
            let imageName = String(describing: NSDate()) + ".png"
            Alamofire.upload(multipartFormData: { multipartFormData in
                multipartFormData.append(datata!, withName: "photo", fileName: imageName, mimeType: "image/png")
                multipartFormData.append(self.name.data(using: String.Encoding.utf8)!, withName: "name")
            }, to: "https://www.beidikeji.com/life/public/jiekou/shoppicture?", encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { Request in
                            switch Request.result {
                            case .success: break
                            case .failure: break
                        }
                }
                    self.noticeInfo("照片修改成功", autoClear: true, autoClearTime: 2)
                case .failure( _):
                    self.noticeInfo("照片修改失败", autoClear: true, autoClearTime: 2)
                }
            
        })
        picker.dismiss(animated:true, completion:nil)
    }

}
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
    
    //点击return 收回键盘
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: 0)
            self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        }
        return true
    }
    
    //通过委托来实现放弃第一响应者
    //UITextView Delegate  Method
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }


}


